﻿using Microsoft.EntityFrameworkCore;
//using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YougeBookmark.Models;
using YougeBookmark.Utilities;

namespace YougeBookmark.Data
{
    public class BookmarkTagRepository
    {
        private readonly DatabaseContext _context;
        private readonly Logger _logger;

        //public async Task<BookmarkTag> CreateAssociationAsync(int bookmarkId, int tagId)
        //{
        //    try
        //    {
        //        if (await ExistsAsync(bookmarkId, tagId))
        //        {
        //            _logger.Warn($"关联已存在: BookmarkId={bookmarkId}, TagId={tagId}");
        //            return null;
        //        }

        //        var entity = new BookmarkTag
        //        {
        //            BookmarkId = bookmarkId,
        //            TagId = tagId
        //        };

        //        _context.BookmarkTags.Add(entity);
        //        await _context.SaveChangesAsync();
        //        return entity;
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.Error($"创建关联失败: {ex.Message}", ex);
        //        throw;
        //    }
        //}

        // BookmarkTagRepository.cs 添加以下方法
        public async Task CreateAssociationAsync(int bookmarkId, int tagId)
        {
            await AddAsync(bookmarkId, tagId);
        }

        public async Task<bool> DeleteAssociationAsync(int bookmarkId, int tagId)
        {
            return await DeleteAsync(bookmarkId, tagId);
        }

        // BookmarkTagRepository.cs 添加以下方法
        public async Task<int> DeleteByTagAsync(int tagId)
        {
            try
            {
                var records = await _context.BookmarkTags
                    .Where(bt => bt.TagId == tagId)
                    .ToListAsync();

                _context.BookmarkTags.RemoveRange(records);
                return await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.Error($"按标签删除关联失败: {ex.Message}", ex);
                throw;
            }
        }

        public async Task<List<BookmarkTag>> GetByTagAsync(int tagId)
        {
            return await _context.BookmarkTags
                .Where(bt => bt.TagId == tagId)
                .ToListAsync();
        }

        //public async Task<BookmarkTag> CreateAssociationAsync(int bookmarkId, int tagId)
        //{
        //    return await AddAsync(bookmarkId, tagId);
        //}

        public BookmarkTagRepository(DatabaseContext context, Logger logger)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 创建书签-标签关联关系
        /// </summary>
        public async Task<BookmarkTag> AddAsync(int bookmarkId, int tagId)
        {
            try
            {
                if (await ExistsAsync(bookmarkId, tagId))
                {
                    _logger.Warn($"关联已存在: BookmarkId={bookmarkId}, TagId={tagId}");
                    return null;
                }

                var entity = new BookmarkTag
                {
                    BookmarkId = bookmarkId,
                    TagId = tagId
                };

                _context.BookmarkTags.Add(entity);
                await _context.SaveChangesAsync();
                return entity;
            }
            catch (Exception ex)
            {
                _logger.Error($"创建关联失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 批量删除指定书签的所有关联
        /// </summary>
        public async Task<int> DeleteByBookmarkAsync(int bookmarkId)
        {
            try
            {
                var records = await _context.BookmarkTags
                    .Where(bt => bt.BookmarkId == bookmarkId)
                    .ToListAsync();

                if (records.Count == 0) return 0;

                _context.BookmarkTags.RemoveRange(records);
                return await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.Error($"批量删除书签关联失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 删除单个关联关系
        /// </summary>
        public async Task<bool> DeleteAsync(int bookmarkId, int tagId)
        {
            try
            {
                var entity = await _context.BookmarkTags
                    .FirstOrDefaultAsync(bt => bt.BookmarkId == bookmarkId && bt.TagId == tagId);

                if (entity == null) return false;

                _context.BookmarkTags.Remove(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error($"删除关联失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 检查关联关系是否存在
        /// </summary>
        public async Task<bool> ExistsAsync(int bookmarkId, int tagId)
        {
            return await _context.BookmarkTags
                .AnyAsync(bt => bt.BookmarkId == bookmarkId && bt.TagId == tagId);
        }

        /// <summary>
        /// 获取书签的所有关联标签ID
        /// </summary>
        public async Task<List<int>> GetTagIdsByBookmarkAsync(int bookmarkId)
        {
            try
            {
                return await _context.BookmarkTags
                    .Where(bt => bt.BookmarkId == bookmarkId)
                    .Select(bt => bt.TagId)
                    .ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.Error($"获取书签标签失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取标签关联的所有书签ID
        /// </summary>
        public async Task<List<int>> GetBookmarkIdsByTagAsync(int tagId)
        {
            try
            {
                return await _context.BookmarkTags
                    .Where(bt => bt.TagId == tagId)
                    .Select(bt => bt.BookmarkId)
                    .ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.Error($"获取标签书签失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取完整关联实体集合
        /// </summary>
        public async Task<List<BookmarkTag>> GetAllByBookmarkAsync(int bookmarkId)
        {
            return await _context.BookmarkTags
                .Include(bt => bt.Tag)
                .Where(bt => bt.BookmarkId == bookmarkId)
                .ToListAsync();
        }
    }
}